namespace SumerCoreDevOps.Shared.Services;

/// <summary>
/// 版本生成器 - 支持多种版本生成策略
/// </summary>
public class VersionGenerator
{
    /// <summary>
    /// 生成版本号
    /// </summary>
    /// <param name="strategy">生成策略</param>
    /// <param name="baseVersion">基础版本（可选）</param>
    /// <param name="gitTag">Git Tag（可选）</param>
    /// <param name="gitCommitHash">Git Commit Hash（可选）</param>
    /// <returns>生成的版本号</returns>
    public static string Generate(
        VersionStrategy strategy,
        string? baseVersion = null,
        string? gitTag = null,
        string? gitCommitHash = null)
    {
        return strategy switch
        {
            VersionStrategy.GitTag => GenerateFromGitTag(gitTag),
            VersionStrategy.GitCommitHash => GenerateFromCommitHash(gitCommitHash),
            VersionStrategy.Timestamp => GenerateFromTimestamp(),
            VersionStrategy.DateVersion => GenerateFromDate(),
            VersionStrategy.SemanticVersion => GenerateSemanticVersion(baseVersion, gitCommitHash),
            VersionStrategy.Custom => baseVersion ?? "1.0.0",
            _ => "latest"
        };
    }

    /// <summary>
    /// 从 Git Tag 生成版本（去除 v 前缀）
    /// 示例: v1.2.3 -> 1.2.3
    /// </summary>
    private static string GenerateFromGitTag(string? gitTag)
    {
        if (string.IsNullOrEmpty(gitTag))
        {
            return "latest";
        }

        // 去除 v 前缀
        var version = gitTag.TrimStart('v', 'V');

        // 验证是否是有效的版本号格式
        if (System.Text.RegularExpressions.Regex.IsMatch(version, @"^\d+\.\d+(\.\d+)?"))
        {
            return version;
        }

        // 如果不是标准版本号，直接返回tag名
        return gitTag;
    }

    /// <summary>
    /// 从 Git Commit Hash 生成版本
    /// 示例: abc123def -> abc123d
    /// </summary>
    private static string GenerateFromCommitHash(string? commitHash)
    {
        if (string.IsNullOrEmpty(commitHash))
        {
            return "latest";
        }

        // 取前7位
        return commitHash.Length > 7 ? commitHash.Substring(0, 7) : commitHash;
    }

    /// <summary>
    /// 从时间戳生成版本
    /// 示例: 1234567890
    /// </summary>
    private static string GenerateFromTimestamp()
    {
        return DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
    }

    /// <summary>
    /// 从日期生成版本
    /// 示例: 20250101.123456 (年月日.时分秒)
    /// </summary>
    private static string GenerateFromDate()
    {
        var now = DateTime.UtcNow;
        return $"{now:yyyyMMdd}.{now:HHmmss}";
    }

    /// <summary>
    /// 生成语义化版本（SemVer）
    /// 示例: 1.0.0-abc123d
    /// </summary>
    private static string GenerateSemanticVersion(string? baseVersion, string? commitHash)
    {
        var version = baseVersion ?? "1.0.0";

        if (!string.IsNullOrEmpty(commitHash))
        {
            var shortHash = commitHash.Length > 7 ? commitHash.Substring(0, 7) : commitHash;
            return $"{version}-{shortHash}";
        }

        return version;
    }

    /// <summary>
    /// 生成 Docker 镜像标签
    /// </summary>
    /// <param name="imageName">镜像名称</param>
    /// <param name="strategy">版本策略</param>
    /// <param name="baseVersion">基础版本</param>
    /// <param name="gitTag">Git Tag</param>
    /// <param name="gitCommitHash">Git Commit Hash</param>
    /// <param name="includeLatesttag">是否同时生成 latest 标签</param>
    /// <returns>Docker 镜像标签列表</returns>
    public static List<string> GenerateDockerTags(
        string imageName,
        VersionStrategy strategy,
        string? baseVersion = null,
        string? gitTag = null,
        string? gitCommitHash = null,
        bool includeLatestTag = true)
    {
        var tags = new List<string>();

        // 主版本标签
        var version = Generate(strategy, baseVersion, gitTag, gitCommitHash);
        tags.Add($"{imageName}:{version}");

        // 可选的 latest 标签
        if (includeLatestTag)
        {
            tags.Add($"{imageName}:latest");
        }

        // 如果是 Git Tag 策略，还可以添加主次版本号
        if (strategy == VersionStrategy.GitTag && !string.IsNullOrEmpty(gitTag))
        {
            var cleanVersion = gitTag.TrimStart('v', 'V');
            var parts = cleanVersion.Split('.');

            if (parts.Length >= 2)
            {
                // 添加主版本号标签: 1
                tags.Add($"{imageName}:{parts[0]}");

                // 添加主次版本号标签: 1.2
                tags.Add($"{imageName}:{parts[0]}.{parts[1]}");
            }
        }

        return tags.Distinct().ToList();
    }

    /// <summary>
    /// 解析版本策略配置字符串
    /// </summary>
    public static VersionStrategy ParseStrategy(string? strategyStr)
    {
        if (string.IsNullOrEmpty(strategyStr))
        {
            return VersionStrategy.Timestamp;
        }

        return strategyStr.ToLowerInvariant() switch
        {
            "tag" or "git-tag" or "gittag" => VersionStrategy.GitTag,
            "commit" or "git-commit" or "commit-hash" => VersionStrategy.GitCommitHash,
            "timestamp" or "unix" => VersionStrategy.Timestamp,
            "date" or "datetime" => VersionStrategy.DateVersion,
            "semver" or "semantic" => VersionStrategy.SemanticVersion,
            "custom" => VersionStrategy.Custom,
            _ => VersionStrategy.Timestamp
        };
    }
}

/// <summary>
/// 版本生成策略
/// </summary>
public enum VersionStrategy
{
    /// <summary>
    /// 使用 Git Tag 作为版本（去除 v 前缀）
    /// 示例: v1.2.3 -> 1.2.3
    /// </summary>
    GitTag,

    /// <summary>
    /// 使用 Git Commit Hash（前7位）
    /// 示例: abc123def -> abc123d
    /// </summary>
    GitCommitHash,

    /// <summary>
    /// 使用 Unix 时间戳
    /// 示例: 1234567890
    /// </summary>
    Timestamp,

    /// <summary>
    /// 使用日期时间
    /// 示例: 20250101.123456
    /// </summary>
    DateVersion,

    /// <summary>
    /// 语义化版本（基础版本 + commit hash）
    /// 示例: 1.0.0-abc123d
    /// </summary>
    SemanticVersion,

    /// <summary>
    /// 自定义版本（直接使用提供的版本号）
    /// </summary>
    Custom
}
